import sqlite3
import os
import logging
from logging_config import setup_logging

# 配置日志
logging.basicConfig(
    level=logging.INFO,
    format='%(asctime)s - %(name)s - %(levelname)s - %(message)s'
)
logger = logging.getLogger('sync')

# 数据库文件路径
DB_PATH = os.path.join('db', 'sync.db')

def delete_sync_dir(sync_dir_id):
    """删除同步目录及其相关记录"""
    try:
        # 连接数据库
        conn = sqlite3.connect(DB_PATH)
        conn.row_factory = sqlite3.Row
        cursor = conn.cursor()

        # 开始事务
        cursor.execute('BEGIN TRANSACTION')

        try:
            # 删除同步历史记录
            cursor.execute('DELETE FROM sync_history WHERE sync_dir_id = ?', (sync_dir_id,))
            logger.info(f"已删除同步目录 {sync_dir_id} 的历史记录")

            # 删除同步目录记录
            cursor.execute('DELETE FROM sync_dirs WHERE id = ?', (sync_dir_id,))
            logger.info(f"已删除同步目录 {sync_dir_id} 的记录")

            # 提交事务
            conn.commit()
            logger.info(f"成功删除同步目录 {sync_dir_id} 的所有记录")
            return True

        except Exception as e:
            # 如果出错，回滚事务
            conn.rollback()
            logger.error(f"删除同步目录 {sync_dir_id} 失败: {str(e)}")
            return False

        finally:
            conn.close()

    except Exception as e:
        logger.error(f"数据库操作失败: {str(e)}")
        return False

if __name__ == '__main__':
    # 删除ID为27的同步目录
    if delete_sync_dir(27):
        print("同步目录删除成功")
    else:
        print("同步目录删除失败") 